
import echarts from 'echarts';
// 引入柱状图
import 'echarts/lib/chart/bar';
// 引入提示框和标题组件
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/title';

function MainController($http, $scope, $timeout, ngDialog) {
  'ngInject';

  let _this = this;

  // 获取重点检查项3条
  this.paginationData1 = {
    pageNum: 1,
    pageSize: 3,
    total: '',
  }

  // 获取专项检查任务提醒
  this.paginationDataSpecial = {
    pageNum: 1,
    pageSize: 4,
    total: '',
  }

  // 获取红黑榜6条
  this.paginationData = {
    pageNum: 1,
    pageSize: 6,
    total: '',
  }

  this.getCheckStatus = (status) => {
    switch(status) {
      case 0:
        return '未开始';
        break;
      case 1:
        return '进行中';
        break;
      case 2:
        return '待整改';
        break;
      case 3:
        return '已完成';
        break;
    }
  }

  // 红黑榜数据
  this.topList = {
    redList: [],
    blackList:[]
  };

  // 新增重点检查项
  this.addDialog = function() {
    ngDialog.open({
      template: 'openMainPlan',
      className: 'ngdialog-theme-default pa-special-check-item-list-theme',
      controllerAs: 'vm',
      controller: function addMainCtrl($scope, $http) {
        'ngInject';
        this.outerCheckItemList = [];

        this.treeActive = false; // 不显示tree
        // 打开tree
        this.openTree = () => {
          this.treeActive = true;
        }

        // 关闭tree
        this.closeTree = () => {
          this.treeActive = false;
        };

        // 考核项 => viewModel
        this.handleDataToViewModel = (data) => {
          let _this = this;
          let isDefaultNodeSelected = false;

          function recursionHandleData(data) {
            data.forEach((item) => {
              item.name = item.checkCategoryName;
              item.open = true;
              itemDetail1 = item;
              if (item.sonsList) {
                item.children = item.sonsList;
                recursionHandleData(item.sonsList);
              }
            });
          }
          recursionHandleData(data);
        };

        // 根据数据渲染ztree
        this.renderZtree = () => {
          let _this = this;
          // click触发事件
          function zTreeOnCheck(event, treeId, treeNode) {
            var checked = treeNode.checked;
            var rootNode = angular.copy(treeNode);
            while (rootNode && rootNode.getParentNode()) {
              rootNode = rootNode.getParentNode();
            }
            var rootNodeName = rootNode.name;

            $scope.$apply(() => {
              if (!treeNode.isParent) {
                checked ? addItem(treeNode) : deleteItem(treeNode);
              } else {
                checked ? recursionAddItem(treeNode) : recursionDelItem(treeNode);
              }
            });

            function addItem(node) {
              if (rootNode.name == '内业') {
                _this.innerCheckItemList.push(node);
              } else if (rootNode.checkCategoryName == '外业') {
                _this.outerCheckItemList.push(node);
              }
            }

            function deleteItem(node) {
              if (rootNode.name == '内业') {
                _this.innerCheckItemList.splice(node);
              } else if (rootNode.checkCategoryName == '外业') {
                _this.outerCheckItemList.splice(node);
              }
            }

            function recursionAddItem(node) {
              node.children.forEach((item) => {
                if (item.isParent) {
                  recursionAddItem(item);
                } else {
                  addItem(item);
                }
              });
            }

            function recursionDelItem(node) {
              node.children.forEach((item) => {
                if (item.isParent) {
                  recursionDelItem(item);
                } else {
                  deleteItem(item);
                }
              });
            }
          };
          // init jquery-Ztree
          let zTreeObj;
          // zTree 的参数配置，深入使用请参考 API 文档（setting 配置详解）
          let setting = {
            callback: {
              onCheck: zTreeOnCheck,
            },
            check: {
              enable: true,
              chkStyle: "checkbox",
              chkboxType: { "Y": "ps", "N": "ps" }
            },
          };
          // zTree 的数据属性，深入使用请参考 API 文档（zTreeNode 节点数据详解）
          let zNodes = this.categoryList;
          $(document).ready(function(){
            let zTreeObj = $.fn.zTree.init($("#tree"), setting, zNodes);
            /*// 激活默认选中菜单
            let defaultNode = zTreeObj.getNodeByParam('isDefaultNode', true);
            zTreeObj.selectNode(defaultNode);*/
          });
        };

        // 保存添加培训交底
        this.save = () => {
          let reqData = this.newList;
          let outerList = [];
          this.outerCheckItemList.forEach((item) => {
            outerList.push(item.id);
            outerList.push(item.name);
          });
          reqData={
            checkClassifyId : outerList[0],
            checkClassifyName : outerList[1],
          }         
          $http
              .post(`${SERVER_CONTEXT}/api/securityActivities/emphasisWork/addEmphasisWork`,
                reqData)
              .then((resp) => {
                if(resp.data.success){
                  layer.msg('添加安全交底信息成功');
                  $state.reload();
                  $scope.closeThisDialog();
                } 
              });
        }  

        // 初始化弹框页面
        this.initPage = () => {
          let _this = this;
          $http.get(`${SERVER_CONTEXT}/api/safeCheck/safe/select/all`).
          then((data) => {
            if (data.statusText != 'OK') {
            } else {
              _this.categoryList = [];
              _this.categoryList.push(data.data[1]);
              _this.handleDataToViewModel(_this.categoryList);
              _this.renderZtree();
            }
          });
        }
        this.initPage();  
      }
    });
  }

  // 删除重点检查项
  this.deleteKeyItem = (param) => {
    $scope.modalTitle = '删除重点检查项';
    $scope.modalContent = '确认要删除该重点检查项吗?';
    ngDialog.openConfirm({
    template: 'paConfirm',
    className: 'ngdialog-theme-default pa-confirm-theme',
    scope: $scope,
    }).
      then((value) => {
        $http.delete(`${SERVER_CONTEXT}/api/securityActivities/emphasisWork/deleteEmphasisWork/${param}`).
          then((resp) => {
            if(resp.data.success){
              layer.msg(resp.data.message);
              this.getNewItem();
            }           
          });
      }, (reason) => {});
  }

  // 折线图
  this.chartKeyInit = () => {
    // 基于准备好的dom，初始化echarts实例
    var myChart = echarts.init(document.getElementById('inspection-general-section'));
    var option = {
        color: ['#fe6f4d', '#fdc638', '#299be4', '#a9a9a9'],
        title: {
            text: '重点项目安全巡查概况',
            textStyle: {color: '#666'}
        },
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data:['专项检查','日常巡查'],
            top: 25,
            right: 5,
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
        },
        toolbox: {
            feature: {
                saveAsImage: {}
            }
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: _this.nearList.checkClassifyName
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                name:'专项检查',
                type:'line',
                data:_this.nearList.specialCheckTimes
            },
            {
                name:'日常巡查',
                type:'line',
                data:_this.nearList.dailyCheckTimes
            }
        ]
    };
    // 绘制图表
    myChart.setOption(option);
  }

  // 饼状图
  this.timesKeyInit = (data) => {
    var option = {
        color: ['#fe6f4d', '#fdc638', '#299be4', '#a9a9a9', '#2de88f'],
        title : {
            text: '重点巡查次数',
            x:'center',
            textStyle: {color: '#666'}
        },
        tooltip : {
            trigger: 'item',
            formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
            orient: 'vertical',
            left: '10',
            y:'10',
            data: _this.nearList.checkClassifyName
        },
        toolbox: {
            feature: {
                saveAsImage: {}
            }
        },
        series : [
            {
                name: '巡查次数',
                type: 'pie',
                radius : '55%',
                center: ['50%', '60%'],
                data: data,
                itemStyle: {
                    emphasis: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ]
    };
    let myChart = echarts.init(document.getElementById('inspection-times-section'));
    myChart.setOption(option);
  }

  // 柱状图
  this.renderEchartsBar = function() {
    let option = {
      color: ['#6dcbe4', '#2dc3e8'],
      title : {
          text: '安全管理概况',
          textStyle: {color: '#666'}
      },
      tooltip : {
          trigger: 'axis'
      },
      legend: {
          data:['巡查次数','发现问题']
      },
      toolbox: {
          show : true,
          feature : {
              dataView : {show: true, readOnly: false},
              magicType : {show: true, type: ['line', 'bar']},
              restore : {show: true},
              saveAsImage : {show: true}
          }
      },
      calculable : true,
      xAxis : [
          {
              type : 'category',
              data : ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月']
          }
      ],
      yAxis : [
          {
              type : 'value'
          }
      ],
      series : [
          {
              name:'巡查次数',
              type:'bar',
              data:[2, 12, 7, 23, 25, 43, 12, 33, 11, 32, 22, 4],
              markPoint : {
                  data : [
                      {type : 'max', name: '最大值'},
                      {type : 'min', name: '最小值'}
                  ]
              },
              markLine : {
                  data : [
                      {type : 'average', name: '平均值'}
                  ]
              }
          },
          {
              name:'发现问题',
              type:'bar',
              data:[2, 6, 0, 12, 20, 33, 22, 11, 60, 0, 4, 1],
              markPoint : {
                  data : [
                      {name : '年最高', value : 60, xAxis: 8, yAxis: 60},
                      {name : '年最低', value : 0, xAxis: 3, yAxis: 0}
                  ]
              },
              markLine : {
                  data : [
                      {type : 'average', name : '平均值'}
                  ]
              }
          }
      ]
    };
    let myChart = echarts.init(document.getElementById('management-general-section'));
    myChart.setOption(option);
  };
  setTimeout(this.renderEchartsBar, 500);

  var nearDate = new Date();

  // 获取重点项目安全巡查概况
  this.getKeyItem = () => {
    let reqData = {
      queryDate:nearDate
    }
    $http.post(`${SERVER_CONTEXT}/api/securityActivities/specialCheck/queryCheckSituationOverviewByTime`,
      reqData
        )
        .then((resp) => { 
          this.nearQueryList = resp.data;
          let list = {},special = {},daily = {};
          list.checkClassifyName = [];
          list.checkTimes = [];
          special.checkTimes = []; // 专项检查次数
          daily.checkTimes = [] // 日常巡查检查次数

          // 获取重点巡查次数echarts的data
          let dataArr = [];

          // 所有
          this.nearQueryList.all.forEach((item) => {
            list.checkClassifyName.push(item.checkClassifyName);
            list.checkTimes.push(item.checkTimes);
            dataArr.push({
              name:item.checkClassifyName,
              value:item.checkTimes
            })
          });
          // 专项
          this.nearQueryList.special.forEach((item) => {
            special.checkTimes.push(item.checkTimes);            
          });
          // 日常
          this.nearQueryList.daily.forEach((item) => {
            daily.checkTimes.push(item.checkTimes);
          });  
          
          this.nearList = {
            checkClassifyName: list.checkClassifyName,
            specialCheckTimes: special.checkTimes,
            dailyCheckTimes: daily.checkTimes,
            checkTimes: list.checkTimes
          };

          this.chartKeyInit (); // 重点项目安全巡查概况echarts
          this.timesKeyInit(dataArr); // 重点巡查次数echarts
        })
  }

  // 获取重点检查项
  this.getNewItem = () => {
    var mainDate = new Date();
    let reqData = {
      queryDate:mainDate
    }
    $http.post(`${SERVER_CONTEXT}/api/securityActivities/emphasisWork/queryEmphasisWorkListByCondition`,      
      angular.extend(reqData,this.paginationData1)
        )
        .then((resp) => {
          this.newItemList = resp.data.data;
        })
  }

  // 获取专项检查任务提醒
  this.getSpecialItem = () => {
    $http.post(`${SERVER_CONTEXT}/api/securityActivities/specialCheck/querySpecialCheckRemindByCondition`,
          this.paginationDataSpecial
            ).
          then((resp) => {
            this.securityQuestionTotal = resp.data.data;
          });
  }

  // 安全任务问题汇总
  this.getSafeItem = () => {
    $http.post(`${SERVER_CONTEXT}/api/securityActivities/checkProblem/queryCheckProblemListByCondition`,
      this.paginationData
        ).
      then((resp) => {
        this.securityProblems = resp.data.data;
      });
  }

  //获取红榜
  let reqData = {
    rbType:1
  }
  this.getHongBang = () => {
    $http.post(`${SERVER_CONTEXT}/api/redBlack/redBlackList/selectRedBlackList`,
      angular.extend(reqData,this.paginationData)
        )
        .then((resp) => {
          this.topList.redList = resp.data.data;
        })
  }

  // 获取黑榜
  let resHeiData = {
    rbType:0
  }
  this.getHeiBang = () => {
    $http.post(`${SERVER_CONTEXT}/api/redBlack/redBlackList/selectRedBlackList`,
      angular.extend(resHeiData,this.paginationData)
        )
        .then((resp) => {
          this.topList.blackList = resp.data.data;
        });
  }


  this.initPage = () => {
    // 获取重点项目安全巡查概况
    this.getKeyItem();

    // 获取重点检查项
    this.getNewItem();

    // 获取专项检查任务提醒
    this.getSpecialItem();

    // 安全任务问题汇总
    this.getSafeItem();

    // 获取红榜
    this.getHongBang();

    // 获取黑榜
    this.getHeiBang();
  }

  // 初始化页面
  this.initPage();
}

export default MainController;
